

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Fly542">
  <meta name="keywords" content="">
  
    <meta name="description" content="特殊符号说明   符号 说明    $$ Shell本身的PID（ProcessID，即脚本运行的当前进程ID号）   $! Shell最后运行的后台Process的PID(后台运行的最后一个进程的[进程ID]   $? 最后运行的命令的结束代码（返回值）即执行上一个指令的返回值 (显示最后命令的退出状态。0表示没有错误，其他任何值表明有错误)   $$ 显示shell使用的当前选项，与set命令">
<meta property="og:type" content="article">
<meta property="og:title" content="shell常用方法总结">
<meta property="og:url" content="http://fly542.cn/2022/11/30/04DevOps/22shell%E5%B8%B8%E7%94%A8%E8%AF%AD%E6%B3%95%E6%80%BB%E7%BB%93/index.html">
<meta property="og:site_name" content="Fly542 技术沉淀">
<meta property="og:description" content="特殊符号说明   符号 说明    $$ Shell本身的PID（ProcessID，即脚本运行的当前进程ID号）   $! Shell最后运行的后台Process的PID(后台运行的最后一个进程的[进程ID]   $? 最后运行的命令的结束代码（返回值）即执行上一个指令的返回值 (显示最后命令的退出状态。0表示没有错误，其他任何值表明有错误)   $$ 显示shell使用的当前选项，与set命令">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-11-30T02:05:44.000Z">
<meta property="article:modified_time" content="2025-01-17T01:40:03.261Z">
<meta property="article:author" content="Fly542">
<meta property="article:tag" content="linux">
<meta property="article:tag" content="shell">
<meta name="twitter:card" content="summary_large_image">
  
  
  <title>shell常用方法总结 - Fly542 技术沉淀</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"fly542.cn","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fly542 技术沉淀</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="shell常用方法总结">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-11-30 10:05" pubdate>
        2022年11月30日 上午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      5.2k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      43 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">shell常用方法总结</h1>
            
            <div class="markdown-body">
              <h1 id="特殊符号说明"><a href="#特殊符号说明" class="headerlink" title="特殊符号说明"></a>特殊符号说明</h1><table>
<thead>
<tr>
<th>符号</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>$$</td>
<td>Shell本身的PID（ProcessID，即脚本运行的当前进程ID号）</td>
</tr>
<tr>
<td>$!</td>
<td>Shell最后运行的后台Process的PID(后台运行的最后一个进程的[进程ID]</td>
</tr>
<tr>
<td>$?</td>
<td>最后运行的命令的结束代码（返回值）即执行上一个指令的返回值 (显示最后命令的退出状态。0表示没有错误，其他任何值表明有错误)</td>
</tr>
<tr>
<td>$$</td>
<td>显示shell使用的当前选项，与set命令功能相同</td>
</tr>
<tr>
<td>$*</td>
<td>所有参数列表。跟$@类似，可以当作数组用；<br>使用时”$*”和$<em>的行为不同; <br>“$</em>“将所有参数合并成一个字符串<br>$*所有参数逐单词分割</td>
</tr>
<tr>
<td>$@</td>
<td>所有参数列表。使用时”$@”和$@的行为相同;<br>将每个参数保留为独立的字符串</td>
</tr>
<tr>
<td>$#</td>
<td>代表传递给脚本的参数总数（不包括脚本自己的名称）</td>
</tr>
<tr>
<td>$0</td>
<td>Shell本身的文件名</td>
</tr>
<tr>
<td>$1～$n</td>
<td>添加到Shell的各参数值。$1是第1参数、$2是第2参数…</td>
</tr>
</tbody></table>
<figure class="highlight bash"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></div></td><td class="code"><pre><code class="hljs bash"><span class="hljs-meta">#!/bin/bash</span><br><br><span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;Using \$*:&quot;</span><br><span class="hljs-keyword">for</span> arg <span class="hljs-keyword">in</span> $*; <span class="hljs-keyword">do</span><br>    <span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;Argument: <span class="hljs-variable">$arg</span>&quot;</span><br><span class="hljs-keyword">done</span><br><br><span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;&quot;</span><br><span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;Using \&quot;\$*\&quot;:&quot;</span><br><span class="hljs-keyword">for</span> arg <span class="hljs-keyword">in</span> <span class="hljs-string">&quot;$*&quot;</span>; <span class="hljs-keyword">do</span><br>    <span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;Argument: <span class="hljs-variable">$arg</span>&quot;</span><br><span class="hljs-keyword">done</span><br></code></pre></td></tr></table></figure>
<p>输入以下参数验证<code>./script.sh arg1 &quot;arg2 with spaces&quot; arg3</code></p>
<h1 id="比较运算"><a href="#比较运算" class="headerlink" title="比较运算"></a>比较运算</h1><h2 id="文件比较运算符"><a href="#文件比较运算符" class="headerlink" title="文件比较运算符"></a>文件比较运算符</h2><table>
<thead>
<tr>
<th>操作符</th>
<th>解释</th>
<th>示例</th>
</tr>
</thead>
<tbody><tr>
<td>-e filename</td>
<td>如果 filename 存在，则为真</td>
<td>[ -e /var/log/syslog ]</td>
</tr>
<tr>
<td>-b filename</td>
<td>如果 filename 存在且为块文件则为真</td>
<td></td>
</tr>
<tr>
<td>-d filename</td>
<td>如果 filename 为目录，则为真</td>
<td>[ -d /tmp/mydir ]</td>
</tr>
<tr>
<td>-f filename</td>
<td>如果 filename 为常规文件，则为真</td>
<td>[ -f /usr/bin/grep ]</td>
</tr>
<tr>
<td>-L filename</td>
<td>如果 filename 为符号链接，则为真</td>
<td>[ -L /usr/bin/grep ]</td>
</tr>
<tr>
<td>-r filename</td>
<td>如果 filename 可读，则为真</td>
<td>[ -r /var/log/syslog ]</td>
</tr>
<tr>
<td>-w filename</td>
<td>如果 filename 可写，则为真</td>
<td>[ -w /var/mytmp.txt ]</td>
</tr>
<tr>
<td>-c filename</td>
<td>如果filename存在且为字符型特殊文件则为真。</td>
<td>[ -c /var/mytmp]</td>
</tr>
<tr>
<td>-x filename</td>
<td>如果 filename 可执行，则为真</td>
<td>[ -L /usr/bin/grep ]</td>
</tr>
<tr>
<td>-s filename</td>
<td>若文件ilename存在且至少有一个字符则为真</td>
<td></td>
</tr>
<tr>
<td>filename1 -nt filename2</td>
<td>如果 filename1 比 filename2 新，则为真</td>
<td>[ /tmp/install/etc/services -nt /etc/services ]</td>
</tr>
<tr>
<td>filename1 -ot filename2</td>
<td>如果 filename1 比 filename2 旧，则为真</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody></table>
<h2 id="字符串比较"><a href="#字符串比较" class="headerlink" title="字符串比较"></a>字符串比较</h2><table>
<thead>
<tr>
<th>操作符</th>
<th>解释</th>
<th>示例</th>
</tr>
</thead>
<tbody><tr>
<td>-z string</td>
<td>如果 string 长度为零，则为真</td>
<td>[ -z “$myvar” ]</td>
</tr>
<tr>
<td>-n string</td>
<td>如果 string 长度非零，则为真</td>
<td>[ -n “$myvar” ]</td>
</tr>
<tr>
<td>string1 = string2</td>
<td>如果 string1 与 string2 相同，则为真</td>
<td>[ “$myvar” = “one two three” ]</td>
</tr>
<tr>
<td>string1 != string2</td>
<td>如果 string1 与 string2 不同，则为真</td>
<td>[ “$myvar” != “one two three” ]</td>
</tr>
</tbody></table>
<h2 id="数值比较"><a href="#数值比较" class="headerlink" title="数值比较"></a>数值比较</h2><table>
<thead>
<tr>
<th>操作符</th>
<th>解释</th>
<th>示例</th>
</tr>
</thead>
<tbody><tr>
<td>num1 -eq num2</td>
<td>等于</td>
<td>[ 3 -eq $mynum ]</td>
</tr>
<tr>
<td>num1 -ne num2</td>
<td>不等于</td>
<td>[ 3 -ne $mynum ]</td>
</tr>
<tr>
<td>num1 -lt num2</td>
<td>小于</td>
<td>[ 3 -lt $mynum ]</td>
</tr>
<tr>
<td>num1 -le num2</td>
<td>小于或等于</td>
<td>[ 3 -le $mynum ]</td>
</tr>
<tr>
<td>num1 -gt num2</td>
<td>大于</td>
<td>[ 3 -gt $mynum ]</td>
</tr>
<tr>
<td>num1 -ge num2</td>
<td>大于或等于</td>
<td>[ 3 -ge $mynum ]</td>
</tr>
</tbody></table>
<h2 id="与-amp-amp"><a href="#与-amp-amp" class="headerlink" title="|| 与 &amp;&amp;"></a>|| 与 &amp;&amp;</h2><p>&amp;&amp;左边的命令（命令1）<strong>返回真(即返回0，成功被执行）</strong>后，&amp;&amp;右边的命令（命令2）才能够被执行；换句话说，“如果这个命令执行成功&amp;&amp;那么执行这个命令”</p>
<p>||则与&amp;&amp;相反。如果||左边的命令（command1）未执行成功，那么就执行||右边的命令（command2）；或者换句话说，“如果这个命令执行失败了||那么就执行这个命令。</p>
<table>
<thead>
<tr>
<th>脚本内容</th>
<th>输出</th>
</tr>
</thead>
<tbody><tr>
<td>app() {<br/>    return 0<br/>}<br/>app &amp;&amp; echo “3”</td>
<td>3</td>
</tr>
<tr>
<td>app() {<br/>    return 1<br/>}<br/>app || echo “3”</td>
<td>3</td>
</tr>
</tbody></table>
<h1 id="变量"><a href="#变量" class="headerlink" title="变量"></a>变量</h1><table>
<thead>
<tr>
<th>操作符</th>
<th>解释</th>
<th>是否修改原始value</th>
</tr>
</thead>
<tbody><tr>
<td>${value:-word}</td>
<td>当变量未定义或者值为空时,返回值为word的内容,否则返回变量的值.</td>
<td>NO</td>
</tr>
<tr>
<td>${value:=word}</td>
<td>若变量未定义或者值为空时,在返回word的值的同时将word赋值给value</td>
<td>YES</td>
</tr>
<tr>
<td>${value:?message}</td>
<td>若变量以赋值的话,正常替换.否则将消息message送到标准错误输出<br>(若此替换出现在Shell程序中,那么该程序将终止运行)</td>
<td>NO</td>
</tr>
<tr>
<td>${value:+word}</td>
<td>若变量以赋值的话,其值才用word替换,否则不进行任何替换</td>
<td>NO</td>
</tr>
<tr>
<td>${value:offset}</td>
<td>从变量中提取子串,这里offset和length可以是算术表达式.</td>
<td>NO</td>
</tr>
<tr>
<td>${<code>#</code>value}</td>
<td>变量的字符个数</td>
<td>NO</td>
</tr>
<tr>
<td>${value#pattern}<br>${value##pattern}</td>
<td>去掉value中与pattern相匹配的部分,条件是value的开头与pattern相匹配<br>#与##的区别在于一个是最短匹配模式,一个是最长匹配模式.</td>
<td>NO</td>
</tr>
<tr>
<td>${value%pattern}<br>${value%%pattern}</td>
<td>去掉value中从尾部与pattern相匹配的部分,%与%%的区别与#与##一样</td>
<td>NO</td>
</tr>
<tr>
<td>${value/pattern/string}<br>${value//pattern/string}</td>
<td>进行变量内容的替换,把与pattern匹配的部分替换为string的内容,/与//的区别与上同</td>
<td>NO</td>
</tr>
</tbody></table>
<h2 id="判定变量是否是数值"><a href="#判定变量是否是数值" class="headerlink" title="判定变量是否是数值"></a>判定变量是否是数值</h2><p>使用<code>-z &quot;$&#123;p//[0-9]/&#125;&quot; </code> 判定变量是否是数值。原理为<code>//[0-9]/</code> 是一种字符串替换方式，将 <code>p</code> 变量中的数字(0到9)全部替换为空字符串，然后再判断(-z )替换后的字符串是否为空。如果 <code>p</code> 是空字符串或者只由数字组成，则条件为真，返回 true；</p>
<p>其中<code>$&#123;p//[0-9]/&#125;</code>没有修改原始变量 <code>p</code> 的值，因为在 shell 中使用类似的字符串操作符都是返回一个新的字符串，而没有修改原字符串的值.</p>
<p>示例如下:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs bash">p=<span class="hljs-string">&quot;1234&quot;</span><br><span class="hljs-keyword">if</span> [ -z <span class="hljs-string">&quot;<span class="hljs-variable">$&#123;p//[0-9]/&#125;</span>&quot;</span> ]; <span class="hljs-keyword">then</span><br>	<span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;num=<span class="hljs-variable">$p</span>&quot;</span><br><span class="hljs-keyword">else</span><br>	<span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;string&quot;</span><br><span class="hljs-keyword">fi</span><br></code></pre></td></tr></table></figure>

<h1 id="数组"><a href="#数组" class="headerlink" title="数组"></a>数组</h1><ul>
<li>读取数组 格式是：${array_name[index]}</li>
<li>获取数组中的所有元素：使用@ 或 * 可以获取数组中的所有元素，</li>
<li>获取数组的长度：获取数组长度的方法与获取字符串长度的方法相同<h2 id="遍历循环方法"><a href="#遍历循环方法" class="headerlink" title="遍历循环方法"></a>遍历循环方法</h2>有3中方法遍历<h3 id="标准的for循环"><a href="#标准的for循环" class="headerlink" title="标准的for循环"></a>标准的for循环</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-meta">#!/bin/bash</span><br><span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;创建一个数组&quot;</span><br>array=( <span class="hljs-string">&quot;A&quot;</span> B C D 1 2 3 <span class="hljs-string">&quot;4&quot;</span> )<br><br><span class="hljs-comment">#$&#123;#array[@]&#125;获取数组长度用于循环</span><br><span class="hljs-keyword">for</span>(( i=0;i&lt;<span class="hljs-variable">$&#123;#array[@]&#125;</span>;i++)) <span class="hljs-keyword">do</span><br>    <span class="hljs-built_in">echo</span> <span class="hljs-variable">$&#123;array[i]&#125;</span>;<br><span class="hljs-keyword">done</span>;<br></code></pre></td></tr></table></figure>
<h3 id="for-…-in循环方法"><a href="#for-…-in循环方法" class="headerlink" title="for … in循环方法"></a>for … in循环方法</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-meta">#!/bin/bash</span><br><span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;创建一个数组&quot;</span><br>array=( <span class="hljs-string">&quot;A&quot;</span> B C D 1 2 3 <span class="hljs-string">&quot;4&quot;</span> )<br><br><span class="hljs-comment">#也可以写成for element in $&#123;array[*]&#125;</span><br><span class="hljs-keyword">for</span> element <span class="hljs-keyword">in</span> <span class="hljs-variable">$&#123;array[@]&#125;</span><br><span class="hljs-keyword">do</span><br>    <span class="hljs-built_in">echo</span> <span class="hljs-variable">$element</span><br><span class="hljs-keyword">done</span><br><br></code></pre></td></tr></table></figure>
<h3 id="While循环法"><a href="#While循环法" class="headerlink" title="While循环法"></a>While循环法</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-meta">#!/bin/bash</span><br><span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;创建一个数组&quot;</span><br>array=( <span class="hljs-string">&quot;A&quot;</span> B C D 1 2 3 <span class="hljs-string">&quot;4&quot;</span> )<br><br>i=0<br><span class="hljs-comment">#当变量（下标）小于数组长度时进入循环体</span><br><span class="hljs-keyword">while</span> [ <span class="hljs-variable">$i</span> -lt <span class="hljs-variable">$&#123;#array[@]&#125;</span> ]<br><span class="hljs-keyword">do</span>  <br>    <span class="hljs-built_in">echo</span> <span class="hljs-variable">$&#123;array[$i]&#125;</span>  <br>    <span class="hljs-comment">#按下标打印数组元素</span><br>    <span class="hljs-built_in">let</span> i++  <br><span class="hljs-keyword">done</span><br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="将文件内容加载到数组中"><a href="#将文件内容加载到数组中" class="headerlink" title="将文件内容加载到数组中"></a>将文件内容加载到数组中</h2><p>文件的内容以空格为分隔每个数组元素</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-meta">#!/bin/bash</span><br><br>file=<span class="hljs-string">&quot;./test_file.log&quot;</span><br>array=(`cat <span class="hljs-variable">$&#123;file&#125;</span> `)<br><span class="hljs-keyword">for</span> line <span class="hljs-keyword">in</span> <span class="hljs-variable">$&#123;array[@]&#125;</span><br><span class="hljs-keyword">do</span><br>    <span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;line=<span class="hljs-variable">$&#123;line&#125;</span>&quot;</span><br><span class="hljs-keyword">done</span><br></code></pre></td></tr></table></figure>

<p>test_file.log内容如下</p>
<figure class="highlight mipsasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs mipsasm">aaa mm<br><span class="hljs-keyword">bbbb </span>cccc<br>ddd2<br></code></pre></td></tr></table></figure>

<p>结果输出为</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs ini"><span class="hljs-attr">line</span>=aaa<br><span class="hljs-attr">line</span>=mm<br><span class="hljs-attr">line</span>=bbbb<br><span class="hljs-attr">line</span>=cccc<br><span class="hljs-attr">line</span>=ddd2<br></code></pre></td></tr></table></figure>


<h1 id="实用语句"><a href="#实用语句" class="headerlink" title="实用语句"></a>实用语句</h1><ul>
<li><p>杀掉除今天和pid=1的所有/bin/bash进程</p>
<figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs perl">ps -eo pid,lstart,cmd |<span class="hljs-keyword">grep</span> <span class="hljs-string">&quot;/bin/bash&quot;</span> |<span class="hljs-keyword">grep</span> -v <span class="hljs-string">&quot;$(date +&#x27;%b %e&#x27;)&quot;</span> |<span class="hljs-keyword">grep</span> -v <span class="hljs-string">&#x27;^ *1 &#x27;</span> |awk <span class="hljs-string">&#x27;&#123;print $1&#125;&#x27;</span> |xargs -r <span class="hljs-keyword">kill</span> -<span class="hljs-number">9</span><br></code></pre></td></tr></table></figure></li>
<li><p>遍历目录下所有文件</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs bash">directory=<span class="hljs-string">&quot;./example_directory&quot;</span>  <span class="hljs-comment"># Replace with your directory path</span><br><br><span class="hljs-keyword">for</span> file <span class="hljs-keyword">in</span> <span class="hljs-string">&quot;<span class="hljs-variable">$directory</span>&quot;</span>/*; <span class="hljs-keyword">do</span><br>  <span class="hljs-keyword">if</span> [ -f <span class="hljs-string">&quot;<span class="hljs-variable">$file</span>&quot;</span> ]; <span class="hljs-keyword">then</span><br>    <span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;File: <span class="hljs-variable">$file</span>&quot;</span><br>  <span class="hljs-keyword">fi</span><br><span class="hljs-keyword">done</span><br></code></pre></td></tr></table></figure></li>
<li><p>遍历多行变量的每一行数据</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-comment"># 定义一个多行变量</span><br>multi_line=<span class="hljs-string">&quot;apple</span><br><span class="hljs-string">banana</span><br><span class="hljs-string">orange&quot;</span><br><br><span class="hljs-comment"># 使用while循环遍历多行变量的每一行数据</span><br><span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;遍历多行变量的每一行数据：&quot;</span><br><span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;<span class="hljs-variable">$multi_line</span>&quot;</span> | <span class="hljs-keyword">while</span> IFS= <span class="hljs-built_in">read</span> -r line; <span class="hljs-keyword">do</span><br>    <span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;<span class="hljs-variable">$line</span>&quot;</span><br><span class="hljs-keyword">done</span><br></code></pre></td></tr></table></figure></li>
<li><p>按行读取文件，并处理每行的IP地址</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs routeros"><span class="hljs-comment"># 文件路径</span><br><span class="hljs-attribute">file</span>=<span class="hljs-string">&quot;/path/to/file.txt&quot;</span><br><span class="hljs-comment"># 初始化计数器</span><br><span class="hljs-attribute">count</span>=0<br><br><span class="hljs-comment"># IFS为指定分隔符(Internal Field Separator)</span><br><span class="hljs-keyword">while</span> IFS= read -r<span class="hljs-built_in"> ip; </span><span class="hljs-keyword">do</span><br>    echo <span class="hljs-string">&quot;处理IP地址: <span class="hljs-variable">$ip</span>&quot;</span><br>	# 计数器递增<br>    <span class="hljs-attribute">count</span>=$((count+1))<br>done &lt; <span class="hljs-string">&quot;<span class="hljs-variable">$file</span>&quot;</span><br></code></pre></td></tr></table></figure></li>
<li><p>当执行ssh 命令时while read文件会执行一次就中断，可以使用下面的方式循环</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-meta">#!/bin/bash</span><br><span class="hljs-comment"># 文件路径</span><br>file=<span class="hljs-string">&quot;./m&quot;</span><br><br>cmd=<span class="hljs-string">&quot;ps -eLF|grep mmm |grep -v \&quot;grep\&quot; |grep -v \&quot;ppp\&quot; |wc -l&quot;</span><br><span class="hljs-comment">#cmd=&quot;ps -ef|grep mmm|grep -v \&quot;grep\&quot; |grep -v \&quot;ppp\&quot; |awk &#x27;&#123;print \$2&#125;&#x27;&quot;</span><br>ips=$(cat <span class="hljs-variable">$&#123;file&#125;</span>)<br><span class="hljs-keyword">for</span> ip <span class="hljs-keyword">in</span> <span class="hljs-variable">$ips</span><br><span class="hljs-keyword">do</span><br>    ret=`ssh root@<span class="hljs-string">&quot;<span class="hljs-variable">$&#123;ip&#125;</span>&quot;</span> <span class="hljs-string">&quot;<span class="hljs-variable">$&#123;cmd&#125;</span>&quot;</span>`<br>    <span class="hljs-built_in">echo</span> <span class="hljs-string">&quot;处理IP地址:<span class="hljs-variable">$&#123;ip&#125;</span>, thread=<span class="hljs-variable">$&#123;ret&#125;</span>&quot;</span><br>    <span class="hljs-comment"># 计数器递增</span><br>    <span class="hljs-comment">#count=$((count+1))</span><br><span class="hljs-keyword">done</span><br></code></pre></td></tr></table></figure></li>
<li><p>数字对齐，不足补0</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-meta">#!/bin/bash</span><br><br><span class="hljs-keyword">for</span> ((i=1; i&lt;=400; i++)); <span class="hljs-keyword">do</span><br>    x=<span class="hljs-string">&quot;<span class="hljs-subst">$(printf <span class="hljs-string">&quot;%03d\n&quot;</span> $i)</span> &quot;</span><br>	<span class="hljs-built_in">echo</span> <span class="hljs-variable">$&#123;x&#125;</span><br><span class="hljs-keyword">done</span><br></code></pre></td></tr></table></figure></li>
</ul>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/devops/">devops</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/linux/">linux</a>
                    
                      <a class="hover-with-bg" href="/tags/shell/">shell</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/12/23/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/03linux/11gdb%E8%B0%83%E8%AF%95%E6%8A%80%E5%B7%A7%E6%80%BB%E7%BB%93/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">gdb调试技巧总结</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/11/18/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/03linux/10errno%E8%AF%B4%E6%98%8E/">
                        <span class="hidden-mobile">errno说明</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
